<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>图解 HTTP 缓存 | 砖业洋__</title>
    <meta name="generator" content="VuePress 1.5.2">
    <link rel="icon" href="/haizei.jpg">
    <meta name="description" content="">
    <link rel="preload" href="/assets/css/0.styles.1f351a1e.css" as="style"><link rel="preload" href="/assets/js/app.1c226385.js" as="script"><link rel="preload" href="/assets/js/2.5bd328db.js" as="script"><link rel="preload" href="/assets/js/3.90e623d3.js" as="script"><link rel="preload" href="/assets/js/4.3a00ff1b.js" as="script"><link rel="prefetch" href="/assets/js/10.4eb1cc28.js"><link rel="prefetch" href="/assets/js/11.cd070e67.js"><link rel="prefetch" href="/assets/js/12.0c5442fd.js"><link rel="prefetch" href="/assets/js/5.9f70a21c.js"><link rel="prefetch" href="/assets/js/6.db1982cd.js"><link rel="prefetch" href="/assets/js/7.46572acb.js"><link rel="prefetch" href="/assets/js/8.2b398bc4.js"><link rel="prefetch" href="/assets/js/9.f2979413.js">
    <link rel="stylesheet" href="/assets/css/0.styles.1f351a1e.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container"><!----> <!----> <header class="navbar"><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/" class="home-link router-link-active"><img src="/haizei.jpg" alt="砖业洋__" class="logo"> <span class="site-name can-hide">砖业洋__</span></a> <div class="links"><span>你好，砖业洋__持续为你分享    </span> <div class="search-box"><input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/" class="nav-link">
  首页
</a></div><div class="nav-item"><a href="https://liuchenyang0515.blog.csdn.net" target="_blank" rel="noopener noreferrer" class="nav-link external">
  CSDN主页
  <svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a></div> <!----></nav></div></header> <div class="sidebar-mask"></div> <aside class="sidebar"><nav class="nav-links"><div class="nav-item"><a href="/" class="nav-link">
  首页
</a></div><div class="nav-item"><a href="https://liuchenyang0515.blog.csdn.net" target="_blank" rel="noopener noreferrer" class="nav-link external">
  CSDN主页
  <svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a></div> <!----></nav>  <ul class="sidebar-links"><li><section class="sidebar-group depth-0"><p class="sidebar-heading open"><span>图解 HTTP 缓存</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/tech/tujiehttphuancun.html#强缓存" class="sidebar-link">强缓存</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/tech/tujiehttphuancun.html#○-expires" class="sidebar-link">○ Expires</a></li><li class="sidebar-sub-header"><a href="/tech/tujiehttphuancun.html#○-cache-control" class="sidebar-link">○ Cache-Control</a></li><li class="sidebar-sub-header"><a href="/tech/tujiehttphuancun.html#○-pragma" class="sidebar-link">○ Pragma</a></li></ul></li><li><a href="/tech/tujiehttphuancun.html#协商缓存" class="sidebar-link">协商缓存</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/tech/tujiehttphuancun.html#○-etag-if-none-match" class="sidebar-link">○ ETag/If-None-Match</a></li><li class="sidebar-sub-header"><a href="/tech/tujiehttphuancun.html#○-last-modified-if-modified-since" class="sidebar-link">○ Last-Modified/If-Modified-Since</a></li></ul></li><li><a href="/tech/tujiehttphuancun.html#总结" class="sidebar-link">总结</a><ul class="sidebar-sub-headers"></ul></li></ul></section></li></ul> </aside> <main class="page"> <div class="theme-default-content content__default"><h1 id="图解-http-缓存"><a href="#图解-http-缓存" class="header-anchor">#</a> 图解 HTTP 缓存</h1> <blockquote><p>作者：政采云前端团队</p></blockquote> <h1 id="前言"><a href="#前言" class="header-anchor">#</a> 前言</h1> <p>HTTP 的缓存机制，可以说这是前端工程师需要掌握的重要知识点之一。本文将针对 HTTP 缓存整体的流程做一个详细的讲解，争取做到大家读完整篇文章后，对缓存有一个整体的了解。</p> <p>HTTP 缓存分为 2 种，一种是强缓存，另一种是协商缓存。主要作用是可以加快资源获取速度，提升用户体验，减少网络传输，缓解服务端的压力。这是缓存运作的一个整体流程图：
<img src="/assets/img/tjhttp_1.940f6afe.png" alt="tjhttp_1"></p> <h2 id="强缓存"><a href="#强缓存" class="header-anchor">#</a> 强缓存</h2> <p>不需要发送请求到服务端，直接读取浏览器本地缓存，在 Chrome 的 Network 中显示的 HTTP 状态码是 200 ，在 Chrome 中，强缓存又分为 Disk Cache (存放在硬盘中)和 Memory Cache (存放在内存中)，存放的位置是由浏览器控制的。是否强缓存由 Expires、Cache-Control 和 Pragma 3 个 Header 属性共同来控制。</p> <h3 id="○-expires"><a href="#○-expires" class="header-anchor">#</a> ○ Expires</h3> <p>Expires 的值是一个 HTTP 日期，在浏览器发起请求时，会根据系统时间和 Expires 的值进行比较，如果系统时间超过了 Expires 的值，缓存失效。由于和系统时间进行比较，所以当系统时间和服务器时间不一致的时候，会有缓存有效期不准的问题。Expires 的优先级在三个 Header 属性中是最低的。</p> <h3 id="○-cache-control"><a href="#○-cache-control" class="header-anchor">#</a> ○ Cache-Control</h3> <p>Cache-Control 是 HTTP/1.1 中新增的属性，在请求头和响应头中都可以使用，常用的属性值如有：</p> <ul><li>max-age：单位是秒，缓存时间计算的方式是距离发起的时间的秒数，超过间隔的秒数缓存失效</li> <li>no-cache：不使用强缓存，需要与服务器验证缓存是否新鲜</li> <li>no-store：禁止使用缓存（包括协商缓存），每次都向服务器请求最新的资源</li> <li>private：专用于个人的缓存，中间代理、CDN 等不能缓存此响应</li> <li>public：响应可以被中间代理、CDN 等缓存</li> <li>must-revalidate：在缓存过期前可以使用，过期后必须向服务器验证</li></ul> <h3 id="○-pragma"><a href="#○-pragma" class="header-anchor">#</a> ○ Pragma</h3> <p>Pragma 只有一个属性值，就是 no-cache ，效果和 Cache-Control 中的 no-cache 一致，不使用强缓存，需要与服务器验证缓存是否新鲜，在 3 个头部属性中的优先级最高。</p> <p>本地通过 express 起一个服务来验证强缓存的 3 个属性，代码如下：</p> <div class="language-javascript extra-class"><pre class="language-javascript"><code><span class="token keyword">const</span> express <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'express'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> app <span class="token operator">=</span> <span class="token function">express</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">var</span> options <span class="token operator">=</span> <span class="token punctuation">{</span> 
  etag<span class="token operator">:</span> <span class="token boolean">false</span><span class="token punctuation">,</span> <span class="token comment">// 禁用协商缓存</span>
  lastModified<span class="token operator">:</span> <span class="token boolean">false</span><span class="token punctuation">,</span> <span class="token comment">// 禁用协商缓存</span>
  <span class="token function-variable function">setHeaders</span><span class="token operator">:</span> <span class="token punctuation">(</span><span class="token parameter">res<span class="token punctuation">,</span> path<span class="token punctuation">,</span> stat</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
    res<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token string">'Cache-Control'</span><span class="token punctuation">,</span> <span class="token string">'max-age=10'</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// 强缓存超时时间为10秒</span>
  <span class="token punctuation">}</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
app<span class="token punctuation">.</span><span class="token function">use</span><span class="token punctuation">(</span>express<span class="token punctuation">.</span><span class="token function">static</span><span class="token punctuation">(</span><span class="token punctuation">(</span>__dirname <span class="token operator">+</span> <span class="token string">'/public'</span><span class="token punctuation">)</span><span class="token punctuation">,</span> options<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
app<span class="token punctuation">.</span><span class="token function">listen</span><span class="token punctuation">(</span><span class="token number">3000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div><p>第一次加载，页面会向服务器请求数据，并在 Response Header 中添加 Cache-Control ，过期时间为 10 秒。
<img src="/assets/img/tjhttp_2.7390545f.png" alt="tjhttp_2"></p> <p>第二次加载，Date 头属性未更新，可以看到浏览器直接使用了强缓存，实际没有发送请求。</p> <p><img src="/assets/img/tjhttp_3.a31f7a2b.png" alt="tjhttp_3"></p> <p>过了 10 秒的超时时间之后，再次请求资源：</p> <p><img src="/assets/img/tjhttp_4.caaaedba.png" alt="tjhttp_4"></p> <p>当 Pragma 和 Cache-Control 同时存在的时候，Pragma 的优先级高于 Cache-Control。</p> <p><img src="/assets/img/tjhttp_5.36fe347c.png" alt="tjhttp_5"></p> <h2 id="协商缓存"><a href="#协商缓存" class="header-anchor">#</a> 协商缓存</h2> <p>当浏览器的强缓存失效的时候或者请求头中设置了不走强缓存，并且在请求头中设置了If-Modified-Since 或者 If-None-Match 的时候，会将这两个属性值到服务端去验证是否命中协商缓存，如果命中了协商缓存，会返回 304 状态，加载浏览器缓存，并且响应头会设置 Last-Modified 或者 ETag 属性。</p> <h3 id="○-etag-if-none-match"><a href="#○-etag-if-none-match" class="header-anchor">#</a> ○ ETag/If-None-Match</h3> <p>ETag/If-None-Match 的值是一串 hash 码，代表的是一个资源的标识符，当服务端的文件变化的时候，它的 hash码会随之改变，通过请求头中的 If-None-Match 和当前文件的 hash 值进行比较，如果相等则表示命中协商缓存。ETag 又有强弱校验之分，如果 hash 码是以 &quot;W/&quot; 开头的一串字符串，说明此时协商缓存的校验是弱校验的，只有服务器上的文件差异（根据 ETag 计算方式来决定）达到能够触发 hash 值后缀变化的时候，才会真正地请求资源，否则返回 304 并加载浏览器缓存。</p> <h3 id="○-last-modified-if-modified-since"><a href="#○-last-modified-if-modified-since" class="header-anchor">#</a> ○ Last-Modified/If-Modified-Since</h3> <p>Last-Modified/If-Modified-Since 的值代表的是文件的最后修改时间，第一次请求服务端会把资源的最后修改时间放到 Last-Modified 响应头中，第二次发起请求的时候，请求头会带上上一次响应头中的 Last-Modified 的时间，并放到 If-Modified-Since 请求头属性中，服务端根据文件最后一次修改时间和 If-Modified-Since 的值进行比较，如果相等，返回 304 ，并加载浏览器缓存。</p> <p>本地通过 express 起一个服务来验证协商缓存，代码如下：</p> <div class="language-javascript extra-class"><pre class="language-javascript"><code><span class="token keyword">const</span> express <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'express'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> app <span class="token operator">=</span> <span class="token function">express</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">var</span> options <span class="token operator">=</span> <span class="token punctuation">{</span> 
  etag<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span> <span class="token comment">// 开启协商缓存</span>
  lastModified<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span> <span class="token comment">// 开启协商缓存</span>
  <span class="token function-variable function">setHeaders</span><span class="token operator">:</span> <span class="token punctuation">(</span><span class="token parameter">res<span class="token punctuation">,</span> path<span class="token punctuation">,</span> stat</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
    res<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
      <span class="token string">'Cache-Control'</span><span class="token operator">:</span> <span class="token string">'max-age=00'</span><span class="token punctuation">,</span> <span class="token comment">// 浏览器不走强缓存</span>
      <span class="token string">'Pragma'</span><span class="token operator">:</span> <span class="token string">'no-cache'</span><span class="token punctuation">,</span> <span class="token comment">// 浏览器不走强缓存</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
app<span class="token punctuation">.</span><span class="token function">use</span><span class="token punctuation">(</span>express<span class="token punctuation">.</span><span class="token function">static</span><span class="token punctuation">(</span><span class="token punctuation">(</span>__dirname <span class="token operator">+</span> <span class="token string">'/public'</span><span class="token punctuation">)</span><span class="token punctuation">,</span> options<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
app<span class="token punctuation">.</span><span class="token function">listen</span><span class="token punctuation">(</span><span class="token number">3001</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div><p>第一次请求资源:</p> <p><img src="/assets/img/tjhttp_6.e3c7b6ca.png" alt="tjhttp_6"></p> <p>第二次请求资源，服务端根据请求头中的 If-Modified-Since 和 If-None-Match 验证文件是否修改。</p> <p><img src="/assets/img/tjhttp_7.f3ce1b29.png" alt="tjhttp_7"></p> <p>我们再来验证一下 ETag 在强校验的情况下，只增加一行空格，hash 值如何变化，在代码中，我采用的是对文件进行 MD5 加密来计算其 hash 值。</p> <p>注：只是为了演示用，实际计算不是通过 MD5 加密的，Apache 默认通过 FileEtag 中 FileEtag INode Mtime Size 的配置自动生成 ETag，用户可以通过自定义的方式来修改文件生成 ETag 的方式。</p> <p>为了保证 lastModified 不影响缓存，我把通过 Last-Modified/If-Modified-Since 请求头删除了，源码如下：</p> <div class="language-javascript extra-class"><pre class="language-javascript"><code><span class="token keyword">const</span> express <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'express'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> CryptoJS <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'crypto-js/crypto-js'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> fs <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'fs'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> app <span class="token operator">=</span> <span class="token function">express</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">var</span> options <span class="token operator">=</span> <span class="token punctuation">{</span> 
  etag<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span> <span class="token comment">// 只通过Etag来判断</span>
  lastModified<span class="token operator">:</span> <span class="token boolean">false</span><span class="token punctuation">,</span> <span class="token comment">// 关闭另一种协商缓存</span>
  <span class="token function-variable function">setHeaders</span><span class="token operator">:</span> <span class="token punctuation">(</span><span class="token parameter">res<span class="token punctuation">,</span> path<span class="token punctuation">,</span> stat</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
    <span class="token keyword">const</span> data <span class="token operator">=</span> fs<span class="token punctuation">.</span><span class="token function">readFileSync</span><span class="token punctuation">(</span>path<span class="token punctuation">,</span> <span class="token string">'utf-8'</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// 读取文件</span>
    <span class="token keyword">const</span> hash <span class="token operator">=</span> CryptoJS<span class="token punctuation">.</span><span class="token constant">MD5</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token constant">JSON</span><span class="token punctuation">.</span><span class="token function">stringify</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// MD5加密</span>
    res<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
      <span class="token string">'Cache-Control'</span><span class="token operator">:</span> <span class="token string">'max-age=00'</span><span class="token punctuation">,</span> <span class="token comment">// 浏览器不走强缓存</span>
      <span class="token string">'Pragma'</span><span class="token operator">:</span> <span class="token string">'no-cache'</span><span class="token punctuation">,</span> <span class="token comment">// 浏览器不走强缓存</span>
      <span class="token string">'ETag'</span><span class="token operator">:</span> hash<span class="token punctuation">,</span> <span class="token comment">// 手动设置Etag值为MD5加密后的hash值</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
app<span class="token punctuation">.</span><span class="token function">use</span><span class="token punctuation">(</span>express<span class="token punctuation">.</span><span class="token function">static</span><span class="token punctuation">(</span><span class="token punctuation">(</span>__dirname <span class="token operator">+</span> <span class="token string">'/public'</span><span class="token punctuation">)</span><span class="token punctuation">,</span> options<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
app<span class="token punctuation">.</span><span class="token function">listen</span><span class="token punctuation">(</span><span class="token number">4000</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// 使用新端口号，否则上面验证的协商缓存会一直存在</span>
</code></pre></div><p>第一次和第二次请求如下：</p> <p><img src="/assets/img/tjhttp_8.abf2e733.png" alt="tjhttp_8"></p> <p><img src="/assets/img/tjhttp_9.8749e39f.png" alt="tjhttp_9"></p> <p>然后我修改了 test.js ，增加一个空格后再删除一个空格，保持文件内容不变，但文件的修改时间改变，发起第三次请求，由于我生成 ETag 的方式是通过对文件内容进行 MD5 加密生成，所以虽然修改时间变化了，但请求依然返回了 304 ，读取浏览器缓存。</p> <p><img src="/assets/img/tjhttp_10.a44b8385.png" alt="tjhttp_10"></p> <p>ETag/If-None-Match 的出现主要解决了 Last-Modified/If-Modified-Since 所解决不了的问题：</p> <ul><li>如果文件的修改频率在秒级以下，Last-Modified/If-Modified-Since 会错误地返回 304</li> <li>如果文件被修改了，但是内容没有任何变化的时候，Last-Modified/If-Modified-Since 会错误地返回 304 ，上面的例子就说明了这个问题</li></ul> <h2 id="总结"><a href="#总结" class="header-anchor">#</a> 总结</h2> <p>在实际使用场景中，比如政采云的官网。图片、不常变化的 JS 等静态资源都会使用缓存来提高页面的加载速度。例如政采云首页的顶部导航栏，埋点 SDK 等等。</p> <p>在文章的最后，我们再次回到这张流程图，这张图涵盖了 HTTP 缓存的整体流程，大家对整体流程熟悉后，也可以自己动手通过 Node 来验证下 HTTP 缓存。</p> <p><img src="/assets/img/tjhttp_11.940f6afe.png" alt="tjhttp_11"></p> <br> <!----></div> <footer class="page-edit"><!----> <!----></footer> <!----> </main></div><div class="global-ui"></div></div>
    <script src="/assets/js/app.1c226385.js" defer></script><script src="/assets/js/2.5bd328db.js" defer></script><script src="/assets/js/3.90e623d3.js" defer></script><script src="/assets/js/4.3a00ff1b.js" defer></script>
  </body>
</html>
